package com.zzh.partnersys.im.handler;

import cn.hutool.extra.spring.SpringUtil;
import com.google.gson.Gson;
import com.zzh.partnersys.im.message.request.ApplyAddFriendRequestMessage;
import com.zzh.partnersys.im.session.SessionFactory;
import com.zzh.partnersys.im.rocketmq.contant.MQConstant;
import com.zzh.partnersys.im.rocketmq.producer.MessageSender;
import com.zzh.partnersys.im.sensitiveword.algorithm.SensitiveWordBs;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * @author ??????
 * @version 1.0
 */
//????????ReplayAddFriendRequestMessage??????????Handler,???????????????
@Sharable
public class ApplyAddFriendRequestMessageHandler extends SimpleChannelInboundHandler<ApplyAddFriendRequestMessage> {
    Gson gson = new Gson();

    private MessageSender messageSender;

    private SensitiveWordBs sensitiveWordBs;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ApplyAddFriendRequestMessage applyAddFriendRequestMessage) throws Exception {
//        System.out.println("replayAddFriendRequestMessage"+ applyAddFriendRequestMessage);
        //???????????????????
        if (applyAddFriendRequestMessage == null){

        }
        Long toUid = applyAddFriendRequestMessage.getToUid();//???????????
        String content = applyAddFriendRequestMessage.getContent();//???????????

        //????????????
        if (sensitiveWordBs == null){
            sensitiveWordBs = getSensitiveWordBs();
        }
        //??????????
        applyAddFriendRequestMessage.setContent(sensitiveWordBs.filter(content));


        //???????????
        Channel channel = SessionFactory.getSession().getChannel(toUid);
        if (channel != null){
            //??????????????
            System.out.println("????");
            //???TextWebSocketFrame????????????WebSocket)
            //todo {type:3,uid:fromUid,content:content}=>???json
            String json = gson.toJson(applyAddFriendRequestMessage);
            channel.writeAndFlush(new TextWebSocketFrame(json));
        }

        //rocketMQ????????
        if (messageSender == null){
            messageSender = getMessageSender();
        }
        messageSender.sendMsg(MQConstant.ADD_FRIEND_APPLY_TOPIC,applyAddFriendRequestMessage);
    }


    //???Bean????
    protected SensitiveWordBs getSensitiveWordBs(){
        return SpringUtil.getBean(SensitiveWordBs.class);
    }

    protected MessageSender getMessageSender(){
        return SpringUtil.getBean(MessageSender.class);
    }

}
